import 'package:flutter/material.dart';
import 'package:flutter_baselib/flutter_baselib.dart';

///@date:  2021/3/1 11:05
///@author:  lixu
///@description: ViewModel 基类
///进入View页面时，直接显示UI（不需要请求http获取数据）的场景继承[BaseCommonViewModel]类
abstract class BaseCommonViewModel with ChangeNotifier {
  ///是否已经调用了dispose()方法
  bool _isDispose = false;

  ///是否正在请求中
  bool isLoading = false;

  ///网络请求对象，充当MVVM的Model层
  XApi api = XApi();

  ///保存请求token，用于页面关闭时取消请求
  List<CancelToken> cancelTokenList = [];

  String tag = 'BaseCommonViewModel';

  BaseCommonViewModel() {
    tag = getTag();
  }

  ///获取tag,用于日志tag
  String getTag();

  ///加载数据
  Future onLoading(BuildContext context) async {}

  ///请求是否成功
  bool isSuccess() {
    return true;
  }

  ///请求是否失败
  bool isFail() {
    return false;
  }

  ///请求数据是否为空
  bool isEmpty() {
    return false;
  }

  ///刷新页面
  @override
  notifyListeners() {
    LogUtils.v(getTag(), 'notifyListeners() isDispose:$_isDispose');
    if (!_isDispose) {
      super.notifyListeners();
    } else {
      LogUtils.e(getTag(), '在调用notifyListeners()方法之前已经调用了dispose()方法');
    }
  }

  bool get isDispose => _isDispose;

  ///页面关闭时回调该方式，释放资源
  @override
  void dispose() {
    super.dispose();
    api.cancelList(cancelTokenList);
    _isDispose = true;
    LogUtils.v(getTag(), 'dispose()');
  }
}
